package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.dto.FileWatermarkConfigDto;
import cn.cdeden.knowledge.domain.dto.FileWatermarkConfigQueryParam;
import cn.cdeden.knowledge.domain.dto.FileWatermarkInfoDto;
import cn.cdeden.knowledge.enums.FilesWatermarkConfigEnums;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.utils.PageUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.undertow.util.BadRequestException;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cdeden.knowledge.mapper.FilesWatermarkConfigMapper;
import cn.cdeden.knowledge.domain.FilesWatermarkConfig;
import cn.cdeden.knowledge.service.FilesWatermarkConfigService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = FileWatermarkConfigService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FilesWatermarkConfigServiceImpl extends ServiceImpl<FilesWatermarkConfigMapper, FilesWatermarkConfig> implements FilesWatermarkConfigService{

    private final FilesWatermarkConfigMapper fileWatermarkConfigMapper;

    @Override
    public TableDataInfo<FileWatermarkConfigDto> queryAll(FileWatermarkConfigQueryParam query, Pageable pageable) {
        IPage<FilesWatermarkConfig> queryPage = PageUtil.toMybatisPage(pageable);
//        IPage<FileWatermarkConfig> page = fileWatermarkConfigMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        IPage<FilesWatermarkConfig> page = fileWatermarkConfigMapper.selectAll(query,queryPage);
        List<FileWatermarkConfigDto> configDtos = new ArrayList<>();
//        List<DictDetailDto> dictionary = getDictionary();
        List<FilesWatermarkConfigEnums> dictionary = Arrays.asList(FilesWatermarkConfigEnums.values());
        for (FilesWatermarkConfig record : page.getRecords()) {
            FileWatermarkConfigDto convert = MapstructUtils.convert(record, FileWatermarkConfigDto.class);
//            FileWatermarkConfigDto convert = ConvertUtil.convert(record, FileWatermarkConfigDto.class);
            String watermarkInfo = record.getWatermarkInfo();
            List<FileWatermarkInfoDto> infoDtos = JSONArray.parseArray(watermarkInfo, FileWatermarkInfoDto.class);
            convert.setInfoDtos(infoDtos);

            String watermarkTxt = queryExpected(infoDtos, true, dictionary);
            convert.setWatermarkTxt(watermarkTxt);
            configDtos.add(convert);
        }
        return new TableDataInfo<FileWatermarkConfigDto>(configDtos, page.getTotal(), (int) page.getCurrent(), (int) page.getPages());
//        return new PageInfo<>(page.getTotal(),
//            configDtos,
//            pageable.getPageNumber(), pageable.getPageSize());
    }



    @Override
    public String queryExpected(List<FileWatermarkInfoDto> infoDtos, Boolean b, List<FilesWatermarkConfigEnums> dictionary) {
        List<FileWatermarkInfoDto> sort = sort(infoDtos);
        StringBuilder watermarkTxt = new StringBuilder();
        for (FileWatermarkInfoDto infoDto : sort) {
            String value = infoDto.getValue();
            String splice = infoDto.getSplice();
            watermarkTxt.append(value);
            if (StringUtils.isNotEmpty(splice)) { //设置拼接
                watermarkTxt.append(splice);
            }
        }

        String string = watermarkTxt.toString();
        if (b) {
            if (CollectionUtils.isEmpty(dictionary)) {
                dictionary = Arrays.asList(FilesWatermarkConfigEnums.values());
            }
            for (FilesWatermarkConfigEnums detailDto : dictionary) {
                string = string.replace(detailDto.getConfigCode(), "`" + detailDto.getConfigName() + "`");
            }
        }
        return string;
    }

    @Override
    public TableDataInfo<FileWatermarkConfigDto> libraryQuery(FileWatermarkConfigQueryParam query, Pageable pageable) throws BadRequestException {
        //        1.测试验证
        String libraryType = query.getLibraryType(); // 库类型
        TreeEnum treeEnum = TreeEnum.find(libraryType);
        if (treeEnum == null) {
            throw new BadRequestException("库类型错误");
        }
        String ownerId = query.getOwnerId(); // 拥有者编号

        if (!treeEnum.equals(TreeEnum.ENTERPRISE)) {
            throw new BadRequestException("暂时没有开启其他库的水印模块");
        }
        if (treeEnum.equals(TreeEnum.TEAM)){
            if (StringUtils.isEmpty(ownerId)) {
                throw new BadRequestException("该库的所有者编号 不可以为空");
            }
        }else if (treeEnum.equals(TreeEnum.PERSONAL)){
//            ownerId = String.valueOf(FileUserUtils.getUser().getId());
            ownerId = String.valueOf(LoginHelper.getUserId());
        }



//        2.数据查询
        TableDataInfo<FileWatermarkConfigDto> info = this.queryAll(query, pageable);
//        PageInfo<FileWatermarkConfigDto> info = this.queryAll(query, pageable);
        long totalElements = info.getTotal();
//        long totalElements = info.getTotalElements();
//        long totalElements = info.getTotalElements();
        if (totalElements == 0) {
//        3.为空生成默认的水印格式
            FileWatermarkConfigDto configDto = generateDefault(treeEnum, ownerId);
            List<FileWatermarkConfigDto> content = new ArrayList<>();
            content.add(configDto);
            info.setRows(content);
//            info.setContent(content);
            info.setTotal(1);
//            info.setTotalElements(1);

        }
        return info;
    }


    /**
     * @param infoDtos
     * @return java.util.List<com.cdyd.ecm.core.watermark.domain.FileWatermarkInfoDto>
     * @Description // 排序
     **/
    private List<FileWatermarkInfoDto> sort(List<FileWatermarkInfoDto> infoDtos) {

        Collections.sort(infoDtos, new Comparator<FileWatermarkInfoDto>() {
            @Override
            public int compare(FileWatermarkInfoDto o1, FileWatermarkInfoDto o2) {
                Integer o1Sort = o1.getSort();
                Integer o2Sort = o2.getSort();
                if (o1Sort < o2Sort) {
                    return -1;
                }
                return 1;
            }
        });

        return infoDtos;
    }





    /**
     * @param treeEnum
     * @return com.cdyd.ecm.core.watermark.domain.dto.FileWatermarkConfigDto
     * @Description // 生成默认的库的 水印格式
     * @Date 2024/5/17 14:37
     **/
    private FileWatermarkConfigDto generateDefault(TreeEnum treeEnum, String ownerId) throws BadRequestException {
        FileWatermarkConfigDto infoConfig = new FileWatermarkConfigDto();
        List<FileWatermarkInfoDto> infoList = new ArrayList<>();
        switch (treeEnum) {
            case ENTERPRISE:  //企业
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.company_name.getConfigCode())); //公司名称
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.nick_name.getConfigCode())); //用户昵称
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.dept_name.getConfigCode())); //用户部门
                infoConfig.setWatermarkName("企业默认文件水印");
                break;
            case TEAM:  //团队
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.team_name.getConfigCode())); //公司名称
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.nick_name.getConfigCode())); //用户昵称
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.dept_name.getConfigCode())); //用户部门
                infoConfig.setWatermarkName("企业默认文件水印");

                break;
            case PERSONAL: //个人
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.file_name.getConfigCode())); //公司名称
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.nick_name.getConfigCode())); //用户昵称
                infoList.add(new FileWatermarkInfoDto(FilesWatermarkConfigEnums.dept_name.getConfigCode())); //用户部门
                infoConfig.setWatermarkName("企业默认文件水印");
                break;
        }
        infoConfig.setInfoDtos(infoList); //默认的水印规则
        infoConfig.setLibraryType(treeEnum.getType());
        if (ownerId != null) {
            infoConfig.setOwnerId(ownerId);
        }

        infoConfig = insert(infoConfig);
        return infoConfig;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileWatermarkConfigDto insert(FileWatermarkConfigDto resources) throws BadRequestException {
        FilesWatermarkConfig entity = MapstructUtils.convert(resources, FilesWatermarkConfig.class);
//        FilesWatermarkConfig entity = ConvertUtil.convert(resources, FilesWatermarkConfig.class);
        String libraryType = entity.getLibraryType();
        if (StringUtils.isEmpty(libraryType)) {
            throw new BadRequestException("请选择水印库");
        }

        TreeEnum treeEnum = TreeEnum.find(libraryType);
        if (treeEnum == null) {
            throw new BadRequestException("水印库类型错误");
        }
        if (treeEnum.equals(TreeEnum.ENTERPRISE)) {

        } else if (treeEnum.equals(TreeEnum.TEAM)) {
            String ownerId = entity.getOwnerId();
            if (StringUtils.isEmpty(ownerId)) {
                throw new BadRequestException("该库的所有者编号 不可以为空");
            }
        } else {
            if (StringUtils.isEmpty(entity.getOwnerId())){
                entity.setOwnerId(String.valueOf(LoginHelper.getUserId()));
//                entity.setOwnerId(String.valueOf(FileUserUtils.getUser().getId()));
            }
        }


        List<FileWatermarkInfoDto> infoDtos = resources.getInfoDtos();
        if (CollectionUtils.isNotEmpty(infoDtos)) {
            String watermarkTxt = queryExpected(infoDtos, false, null);
            entity.setWatermarkTxt(watermarkTxt);
            String string = JSONObject.toJSONString(infoDtos);
            entity.setWatermarkInfo(string);
            boolean save = this.save(entity);
        }else {
            throw new BadRequestException("水印配置信息不能为空");
        }
        return MapstructUtils.convert(entity, FileWatermarkConfigDto.class);
//        return ConvertUtil.convert(entity, FileWatermarkConfigDto.class);
    }



}
